package com.prawn.search.service;


import com.prawn.search.pojo.Product;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

@Service
public class ProductService {
    private final ElasticsearchTemplate elasticsearchTemplate;
    @Autowired
    public ProductService(ElasticsearchTemplate elasticsearchTemplate) {
        this.elasticsearchTemplate = elasticsearchTemplate;
    }

    public Page<Product> findByKey(int productStatus, String key, int page, int size) {
        Pageable pageable = PageRequest.of(page-1, size);

        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.boolQuery()
                        .must(QueryBuilders.termQuery("productStatus",productStatus))
                        .must(QueryBuilders.multiMatchQuery(key,"productName","productTitle")))
                .withPageable(pageable).build();

        return elasticsearchTemplate.queryForPage(searchQuery, Product.class);
    }
}
